from requests.packages.urllib3.exceptions import InsecureRequestWarning

# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: lenovo by amidoufu
@file: amidoufu.py
@time: 2020/05/06
@function:
"""
import requests
import json
import time
import os
import webbrowser
import re
import emoji
import ssl
import fileinput
import sys
import random
import threading
import pygame
import configparser
import tkinter.messagebox
from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

__headers_web = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}

class quanju:
    shipinmingcheng = ""
    dir = ""
    jishu = 1
    shipinlianjie2 = ""


def chushi():
    if not os.path.exists("./火力快手视频data/"):
        os.makedirs("./火力快手视频data/" )
    quanju.dir = "火力快手视频data/"
    res = requests.get("http://49.232.9.114/index/player", headers=__headers_web, verify=False)
    html = res.text
    shipinlianjie_liebiao_find = r'value=\"(.+?)\".title'
    shipinlianjie2_liebiao_find = r'data-src=\"(.+?)\".data-time'
    wangyetiaozhuan_liebiao_find = r'data-uid=\"(.+?)\".value'
    fabushijian_liebiao_find = r'data-time=\"(.+?)\".data-uid'

    shipinlianjie_liebiao = re.findall(shipinlianjie_liebiao_find, html)
    shipinlianjie2_liebiao = re.findall(shipinlianjie2_liebiao_find, html)
    wangyetiaozhuan_liebiao = re.findall(wangyetiaozhuan_liebiao_find, html)
    fabushijian_liebiao = re.findall(fabushijian_liebiao_find, html)

    if shipinlianjie_liebiao != []:
        print("此次共:" + str(len(shipinlianjie_liebiao)) + "个视频")
        for liebiao_jici in range(0, len(shipinlianjie_liebiao)):
            quanju.shipinlianjie2 = shipinlianjie2_liebiao[liebiao_jici]
            xiazai(shipinlianjie_liebiao[liebiao_jici],wangyetiaozhuan_liebiao[liebiao_jici],fabushijian_liebiao[liebiao_jici])
            quanju.jishu += 1
            time.sleep(3)

def xiazai(xiazaidizhi,tiaozhuan_uid,fabushijian, retry=3):
    '''
    下载视频,显示进度

    :param index:       视频序号
    :param username:    用户名
    :param name:        视频名
    :param url:         视频地址
    :param retry:       重试次数

    :return:            None
    '''
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            r = requests.get("http://49.232.9.114/index/jumpHome?uid=" + tiaozhuan_uid, headers=__headers_web, verify=False)
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            print("HTTPError")
            time.sleep(3)
        except requests.exceptions.ConnectionError:
            print("ConnectionError")
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print("ChunkedEncodingError")
            time.sleep(3)
        except:
            print("Unfortunitely -- An Unknow Error Happened")
            time.sleep(3)
    # print(r.history)
    reditList = r.history  # 可以看出获取的是一个地址序列

    # print(f'获取重定向的历史记录：{reditList}')
    # print(f'获取第一次重定向的headers头部信息：{reditList[0].headers}')
    # print(f'获取重定向最终的url：{reditList[len(reditList) - 1].headers["location"]}')
    if reditList ==[]:
        uid = tiaozhuan_uid
    else:
        recovery1 = reditList
        recovery2 = reditList[0].headers
        recovery3 = reditList[len(reditList) - 1].headers["location"]
        recovery_list = recovery3.split("/")
        uid = recovery_list[4]

    shijianshuzu = time.strptime(fabushijian, "%Y-%m-%d %H:%M:%S")
    fabushijian_zhuanhuan = time.strftime("%Y年%m月%d日%H时%M分%S秒", shijianshuzu)

    quanju.shipinmingcheng = uid + "_" + fabushijian_zhuanhuan


    print(str(quanju.jishu) + ">" + "\n正在下载视频:" + quanju.shipinmingcheng)
    video_down = quanju.dir + quanju.shipinmingcheng + ".mp4"
    if os.path.exists(video_down):
        print("视频已存在")
        return
    else:
        print("视频正在下载")
    try:
        #video_response = requests.get(xiazaidizhi, headers=__headers_web, timeout=15)
        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                video_response = requests.get(xiazaidizhi, headers=__headers_web, timeout=15)
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                print( "HTTPError")
                time.sleep(3)
            except requests.exceptions.ConnectionError:
                print( "ConnectionError")
                time.sleep(3)
            except requests.exceptions.ChunkedEncodingError:
                print( "ChunkedEncodingError")
                time.sleep(3)
            except:
                print( "Unfortunitely -- An Unknow Error Happened")
                time.sleep(3)


        # 保存视频，显示下载进度
        if video_response.status_code == 200:
            video_size = int(video_response.headers['Content-Length'])
            if video_size/1024000 >= 600:
                print("视频超过600M已跳过")
                print("\n")
                return
            else:
                with open(video_down, 'wb') as f:
                    data_length = 0
                    for data in video_response.iter_content(chunk_size=1024):
                        data_length += len(data)
                        f.write(data)
                        done = int(50 * data_length / video_size)
                        sys.stdout.write("\r下载进度: [%s%s]" % (
                            '█' * done, ' ' * (50 - done)))
                        sys.stdout.flush()
            print("\n")



        # 失败重试3次，超过放弃
        elif video_response.status_code != 200 and retry:
            retry -= 1
            xiazai(quanju.shipinlianjie2,tiaozhuan_uid,fabushijian, retry)
        else:
            return
    except Exception as e:
        print('download failed,', quanju.shipinmingcheng, e)
        return None


if __name__ == "__main__":
    chushi()